package service

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"

	datatypes "notabug.org/BigWaffleMonster/ip-checker-telegram-bot/pkg/dataTypes"
)

type MessageService struct {
}

func NewMessageService() *MessageService {
	return &MessageService{}
}

func (s *MessageService) MakeResponseMessage(data datatypes.IpResponseType) string {
  var ipData datatypes.IpResponseType = data
  msg := fmt.Sprintf(`
Query: %s,
Status: %s,
Country: %s,
CountryCode: %s,
Region: %s,
RegionName: %s,
City: %s,
Zip: %s,
Lat: %f,
Lon: %f,
Timezone: %s,
Isp: %s,
Org: %s,
As: %s`,
    ipData.Query, ipData.Status, ipData.Country, ipData.CountryCode, ipData.Region, ipData.RegionName,
    ipData.City, ipData.Zip, ipData.Lat, ipData.Lon, ipData.Timezone, ipData.Isp, ipData.Org,
    ipData.As,
  )

  
  return msg
}

func (s *MessageService) GetIpInfo(ip string) (error, datatypes.MessageErrorType, datatypes.IpResponseType) {
	baseUrl := "http://ip-api.com/json/"
  var data datatypes.IpResponseType

	if response, err := http.Get(baseUrl + ip); err != nil {
    return err, datatypes.MessageErrorType{ErrorMessage: "Request error"}, data
	} else {
    defer response.Body.Close()
    content, err := ioutil.ReadAll(response.Body)

    if err != nil {
      return err, datatypes.MessageErrorType{ErrorMessage: "Can`t read body"}, data
    }

    json.Unmarshal([]byte(content), &data)
	}

  return nil, datatypes.MessageErrorType{ErrorMessage: ""}, data
}
